﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SH
{
    public class shBlob:shISerializeable
    {
        byte[] m_data;
        long m_len = 0;
        public

        shBlob()
        {

        }
        shBlob(long len)
        {
            m_data = new byte[len];

            m_len = len;
        }

        public shBlob(byte[] data)
		{
			if (data.Length != 0)
			{
                m_data = (byte[])data.Clone();
                m_len = data.Length;

			}
			else
			{
                m_len = 0;
            }
		}

        public shBlob( shBlob other)
		{
            if (other.Length != 0)
            {
                m_data = (byte[])other.GetData().Clone();
                m_len = other.Length;

            }
            else
            {
                m_len = 0;
            }
        }

        public void setData(byte[] data, long len)
        {
            if (len != 0 && data.Length != 0 && len <= data.Length)
            {
                m_data = (byte[])data.Clone();
                m_len = len;
            }
            else
            {
                m_len = 0;
            }
        }

        public void atacheData(byte[] data)
        {
            m_data = data;
            m_len = data.Length;
        }

        public byte[] detachData()
        {
            var data = m_data;
            m_len = 0;

            return data;
        }

        public bool writeData(byte[] data,long len, long pos)
        {
            var nLen = Math.Min(len, data.Length);

            if (pos + nLen < m_len)
            {
                Buffer.BlockCopy(data, 0, m_data, (int)pos, (int)nLen);
            }
            else
            {
                return false;
            }


            return true;
        }

        public bool readData(ref byte[] data, ref long len, long pos)
        {
            if (pos >= m_len)
                return false;

            var nLen = Math.Min(m_len - pos, len);

            data = new byte[nLen];

            Buffer.BlockCopy(m_data, (int)pos, data, 0, (int)nLen);


            return true;
        }

        public void Clear()
        {
            m_len = 0;

        }

        public bool Empty()
        {
            return m_len == 0;
        }

        public void Swap(shBlob other)
        {
            var data = other.m_data;

            other.m_data = m_data;

            m_data = data;

            var len = other.m_len;
            other.m_len = m_len;
            m_len = len;
        }

        public byte[] GetData()
        {
            return m_data;
        }

        long Length { get => m_len; }

      public  shISerializer serialize(shISerializer sc)
        {
            if(sc.isRead())
            {
                sc.Read(ref m_data,ref m_len);
            }
            else
            {
                sc.Write(m_data,m_len);
              
            }
          
            return sc;
        }
    }
}
